//
//  UIImageView+FadeWebCache.m
//  FadeSDWebImage
//
//  Created by 冷悦 on 16/2/22.
//  Copyright © 2016年 冷悦. All rights reserved.
//

#import "UIImageView+FadeWebCache.h"
#import "UIImageView+WebCache.h"
#import <objc/runtime.h>
#import "NSString+Reform.h"

static const void *FadeTimeKey = &FadeTimeKey;
static const void *PlaceHolderKey = &PlaceHolderKey;

@implementation UIImageView (FadeWebCache)
@dynamic fadeTime;
@dynamic placeHolder;

- (NSNumber *)fadeTime{
    NSNumber *fadeTime = objc_getAssociatedObject(self, FadeTimeKey);
    
    if (fadeTime == nil) {
        
#ifndef kFadeWebCacheFadeTime
#define kFadeWebCacheFadeTime @0.5
#endif
        fadeTime = kFadeWebCacheFadeTime;
    }
    
    return fadeTime;
}

- (void)setFadeTime:(NSNumber *)fadeTime {
    objc_setAssociatedObject(self, FadeTimeKey, fadeTime, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (NSString *)placeHolder{
    NSString *placeHolder = objc_getAssociatedObject(self, PlaceHolderKey);
    
    if (placeHolder == nil) {
#ifndef kFadeWebCachePlaceHolder
#define kFadeWebCachePlaceHolder nil
#endif
        placeHolder = kFadeWebCachePlaceHolder;
    }
    
    return placeHolder;
}

- (void)setPlaceHolder:(NSString *)placeHolder{
    objc_setAssociatedObject(self, PlaceHolderKey, placeHolder, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (void)setImageWithURLString:(nonnull NSString *)urlString
        withPlaceHolderString:(nullable NSString *)placeHolderString
                  andFadeTime:(nullable NSNumber *)fadeTime{
    self.placeHolder = placeHolderString;
    self.fadeTime = fadeTime;
    UIImage *placeHolderImage;
    
    if (self.placeHolder != nil) {
        placeHolderImage = [UIImage imageNamed:self.placeHolder];
    }
    
    if (![urlString containsString:@"http"]) {
        urlString = [NSString pictureAbsolutePathStrWithRelativePathStr:urlString];
    }
    
    NSURL *imageURL = [NSURL URLWithString:urlString];
    
    DDLogInfo(@"需加载的图片地址：%@",urlString);
    
    [self sd_setImageWithURL:imageURL
            placeholderImage:placeHolderImage
                   completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        self.alpha = 0.0;
        [UIView animateWithDuration:[self.fadeTime floatValue] animations:^{
            self.alpha = 1.0;
        }];
    }];
}

- (void)setImageWithURLString:(nonnull NSString *)urlString
         andPlaceHolderString:(nullable NSString *)placeHolderString{
    [self setImageWithURLString:urlString withPlaceHolderString:placeHolderString andFadeTime:nil];
}

- (void)setImageWithURLString:(nonnull NSString *)urlString
                  andFadeTime:(nullable NSNumber *)fadeTime{
    [self setImageWithURLString:urlString withPlaceHolderString:nil andFadeTime:fadeTime];
}

- (void)setImageWithURLString:(nonnull NSString *)urlString{
    [self setImageWithURLString:urlString withPlaceHolderString:nil andFadeTime:nil];
}

@end

















